# == Schema Information
# Schema version: 8
#
# Table name: tickets
#
#  id           :integer(11)   not null, primary key
#  title        :string(255)   default(""), not null
#  created_by   :integer(11)
#  updated_by   :integer(11)
#  assign_to_id :integer(11)
#  status_id    :integer(11)   default(1), not null
#  description  :text
#  created_on   :datetime
#  updated_on   :datetime
#

class Ticket < ActiveRecord::Base

  acts_as_textiled :description

  validates_presence_of :title

  belongs_to(:created_by, :class_name => 'User', :foreign_key => 'created_by')
  belongs_to(:updated_by, :class_name => 'User', :foreign_key => 'updated_by')
  belongs_to(:assign_to, :class_name => 'User', :foreign_key => 'assign_to_id')
  belongs_to(:status)

  has_many :ticket_changes

  def change(ticket_attr, change_attr)
    log = diff(Ticket.new(ticket_attr))
    if update_attributes(ticket_attr)
      ticket_change = TicketChange.new(change_attr.merge(:log => log))
      if ticket_changes << ticket_change
        ticket_change
      end
    end
  end

    private

  def diff(new)
    log = ''
    if status != new.status and new.status
      log << "Status: #{self.status.name} => #{new.status.name} \n"
    end

    if assign_to != new.assign_to and new.assign_to
      log << "Owner: assign to #{new.assign_to.login}"
    end
    log
  end

end
